var list="7654321".split(""), result;
function swap(i,j) {
    tmp = list[i];
    list[i] = list[j];
    list[j] = tmp;
}

function isPrime(num) {
    if(num%2==0) {
        //print(num + "/2");
        return false;
    }
    if(num%3==0) {
        //print(num + "/3");
        return false;
    }
    var sqrt = Math.floor(Math.sqrt(num));
    for(var i=3; i<=sqrt; i=i+2) {
        if(num%i==0) {
            print(num + "/" + i);
            return false;
        }
    }
    return true;
}

function test(list) {
    var tmp = parseInt(list.join(""),10);
    if(isPrime(tmp)) return true;
    return false;
}

function perm(k,m) {
    if(k>m) {
        if(test(list)) {
            result = list.map(function(a) {return a;});
            print(list.join(""));
            quit();
        }
    } else {
        var pass=true;
        for(var i=0; i<k; i++) {
            if(result && parseInt(result[i],10) > parseInt(list[i],10)) {
                pass=false;
                break;
            }
        }
        if(pass) {
            for(var i=k; i<=m; i++) {
                swap(k, i);
                perm(k+1, m);
                swap(k, i);
            }
        }
    }
}

print('get primes.....');
var t=new Date().getTime();
perm(0,9);
print('get primes done..... ' + ((new Date().getTime()-t)/1000) + "s");
